package com.sdy.supermarket.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.model.FileObj;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.MapUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.fs.api.FsApi;
import com.sdy.mvc.utils.JsonUtil;
import com.sdy.supermarket.biz.model.GsRes;
import com.sdy.supermarket.biz.model.GsResIntention;
import com.sdy.supermarket.biz.mapper.GsResIntentionMapper;
import com.sdy.supermarket.biz.model.GsResIntentionRemark;
import com.sdy.supermarket.biz.service.GsResIntentionRemarkService;
import com.sdy.supermarket.biz.service.GsResIntentionService;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.supermarket.biz.service.GsResService;
import com.sdy.supermarket.biz.utils.FileUtil;
import com.sdy.supermarket.biz.vo.ResIntentionVO;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 资源意向表 服务实现类
 * </p>
 *
 * @author zzq
 * @since 2019-08-08
 */
@Slf4j
@Service
public class GsResIntentionServiceImpl extends BaseServiceImpl<GsResIntention> implements GsResIntentionService {
    @Resource
    private GsResIntentionMapper gsResIntentionMapper;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private GsResService gsResService;
    @Autowired
    private FsApi fsApi;
    @Autowired
    private GsResIntentionRemarkService gsResIntentionRemarkService;

    @Override
    public GsResIntention createIntention(GsResIntention intention) {
        UserDTO user = userQueryApi.getUser(intention.getUserId());
        GsRes res = gsResService.getById(intention.getResId());
        intention.setCreateTime(new Date());
        intention.setState(1);
        intention.setDeptName(user.getOwnDeptName());
        intention.setUserName(user.getName());
        intention.setResName(res.getName());
        intention.setPhone(user.getPhone());
        save(intention);
        return intention;
    }

    @Override
    public ResIntentionVO getIntention(Integer intentionId) throws BizException {
        GsResIntention intention = getById(intentionId);
        Assert.isNull(intention, "未查到相关数据");
        ResIntentionVO vo = JsonUtil.convert(intention, ResIntentionVO.class);
        // 备注数据
        List<GsResIntentionRemark> remarkList = gsResIntentionRemarkService
                .lambdaQuery()
                .eq(GsResIntentionRemark::getIntentionId, intentionId)
                .orderByDesc(GsResIntentionRemark::getId)
                .list();
        if (!remarkList.isEmpty()) {
            List<UserDTO> userList = userQueryApi.listUser(remarkList.stream()
                    .map(GsResIntentionRemark::getOpUserId)
                    .collect(Collectors.toList()));
            var userMap = MapUtil.collectionToMap(userList, UserDTO::getId);
            remarkList.forEach(item -> {
                var user = userMap.get(item.getOpUserId());
                if (user != null) {
                    item.setOpUserName(user.getName());
                    item.setOpDeptName(user.getOwnDeptName());
                }
                item.setFileObjList(JsonUtil.convertJsonToFileObjs(item.getFile()));
                item.setFile(null);
            });
        }
        vo.setRemarkList(remarkList);
        return vo;
    }

    @Override
    @SuppressWarnings("unchecked")
    public IPage<ResIntentionVO> pageIntention(Page<GsResIntention> page, String userName, String contact, Integer state) {
        LambdaQueryWrapper<GsResIntention> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(state != null, GsResIntention::getState, state);
        if (StringUtil.isNotBlank(userName)) {
            wrapper.and(wp -> wp.like(GsResIntention::getUserName, userName));
        }
        if (StringUtil.isNotBlank(contact)) {
            wrapper.and(wp2 -> wp2.like(GsResIntention::getPhone, contact));
        }
        wrapper.orderByDesc(GsResIntention::getId);
        IPage<GsResIntention> p = page(page, wrapper);
        IPage<ResIntentionVO> voPage = JsonUtil.convertPage(p, ResIntentionVO.class);
//        for (int i = 0; i < voPage.getRecords().size(); i++) {
//            ResIntentionVO vo = voPage.getRecords().get(i);
//            GsResIntention w = p.getRecords().get(i);
//            vo.setFileObjList(new ArrayList<>());
//            if (StringUtil.isNotBlank(w.getFiles())) {
//                vo.setFileObjList(JsonUtil.fromJson(w.getFiles(), List.class));
//            }
//        }
        return voPage;
    }

    @Override
    public void remarkIntention(Integer intentionId, String content, List<FileObj> files, Integer opUserId) {
        if (files != null) {
            files.forEach(f -> FileUtil.updateFileInfo(f, fsApi));
        }
        gsResIntentionRemarkService.save(
                new GsResIntentionRemark().setIntentionId(intentionId).setFile(JsonUtil.convertFileObjsToJson(files))
                        .setContent(content).setCreateTime(new Date()).setOpUserId(opUserId)
        );
    }

    @Override
    public void doneIntention(Integer intentionId, Integer opUserId) {
        updateById(new GsResIntention()
                .setState(2)
                .setOpUserId(opUserId)
                .setId(intentionId));
    }
}
